package com.binguo.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.enums.*;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.PriceUtil;
import com.binguo.helper.DateHelper;
import com.binguo.model.api.dto.OrderDTO;
import com.binguo.model.api.vo.BinguoOrderVO;
import com.binguo.model.api.vo.OrderVO;
import com.binguo.model.api.vo.OrderVOInWX;
import com.binguo.model.api.vo.SMStatisticsOrderVO;
import com.binguo.model.mapper.BinguoOrderMapper;
import com.binguo.model.mapper.EmployeeLoginHistoryMapper;
import com.binguo.model.model.*;
import com.binguo.model.repository.*;
import com.binguo.common.sms.JavaSmsApi;
import com.binguo.common.sms.SMS;
import com.binguo.model.wxapi.vo.ReserveOrderVO;
import com.binguo.transfer.OrderVOTransfer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.binguo.common.exception.ErrorCode.*;


/**
 * Created by haibang on 18/5/7.
 */
@Service
public class OrderService {

    private static Logger logger = LoggerFactory.getLogger(OrderService.class);


    @Autowired
    BinguoOrderRepository binguoOrderRepository;

    @Autowired
    DiscountOrderRepository discountOrderRepository;

    @Autowired
    OrderItemRepository orderItemRepository;

    @Autowired
    ShopService shopService;

    @Resource
    BinguoOrderMapper binguoOrderMapper;

    @Autowired
    OrderVOTransfer orderVOTransfer;

    @Autowired
    PayCardRepository payCardRepository;

    @Autowired
    CashierDeskRepository cashierDeskRepository;

    @Resource
    EmployeeLoginHistoryMapper employeeLoginHistoryMapper;

    @Autowired
    ShiminkaRechargeDiscountRepository shiminkaRechargeDiscountRepository;

    @Autowired
    ShiminkaRechargeRepository shiminkaRechargeRepository;

    @Autowired
    CustomerService customerService;

    @Autowired
    ProductSourceInfoRepository productSourceInfoRepository;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");

    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");



    public ProductSourceInfo getProductSourceInfo(Integer productId){
        return productSourceInfoRepository.findBy("productId", productId);
    }


    public void updateRefundCardOrder(String orderNo, String transactionId, RefundStatus refundStatus){
        Optional<BinguoOrder> orderOptional = findByRefundStatus(orderNo, RefundStatus.REFUND_DEALING);
        if(orderOptional.isPresent()) {
            BinguoOrder binguoOrder = orderOptional.get();
            binguoOrder.setRefundstatus(refundStatus.getCode().byteValue());
            binguoOrderRepository.update(binguoOrder);
        }

    }


    @Transactional
    public void updateCardOrder(String orderNo, String transactionId, String timeEnd) throws ParseException {
        Optional<BinguoOrder> orderOptional = findByPayStatus(orderNo, PayStatus.PAYING);
        if(orderOptional.isPresent()) {
            BinguoOrder binguoOrder = orderOptional.get();
            binguoOrder.setPaystatus(PayStatus.SUCCESS.getCode().byteValue());
            binguoOrder.setTransactionid(transactionId);
            binguoOrder.setPaytime(simpleDateFormat.parse(timeEnd));
            binguoOrder.setUpdated(new Date());
            binguoOrderRepository.update(binguoOrder);
            //修改payCard的账号余额
            udpatePayCard(binguoOrder.getCardid(), binguoOrder.getRealfee());
        } else {
            throw new ServiceException(WX_ORDER_NOT_EXIST);
        }
    }

    private void udpatePayCard(Integer cardId, Long rechargeFee){
       PayCard payCard = payCardRepository.findById(cardId);
       if(payCard == null) {
           throw new ServiceException(WX_PAYCARD_NOT_EXIST);
       }
       Long newAccountbalance = payCard.getWxAccountbalance() + rechargeFee;
       payCard.setWxAccountbalance(newAccountbalance);
       payCard.setUpdated(new Date());
       payCardRepository.update(payCard);

    }


    public Optional<BinguoOrder> findByOrderNo(String orderNo){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("orderno", orderNo);
        return binguoOrderRepository.findByCondition(condition).stream().findFirst();
    }


    private Optional<BinguoOrder> findByRefundStatus(String orderNo, RefundStatus refundStatus){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("orderno", orderNo)
                .andEqualTo("refundstatus", refundStatus.getCode());
        return binguoOrderRepository.findByCondition(condition).stream().findFirst();
    }

    public Optional<BinguoOrder> findByPayStatus(String orderNo, PayStatus payStatus){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("orderno", orderNo)
                .andEqualTo("paystatus", payStatus.getCode());
        return binguoOrderRepository.findByCondition(condition).stream().findFirst();
    }




    public OrderVO findOneByOrderNo(String orderNo){
        BinguoOrder order = binguoOrderRepository.findBy("orderno", orderNo);
        if(order == null){
            return null;
        } else {
            return orderVOTransfer.toOrderVO(order);
        }
    }

    public OrderVO findOneByOrderNo2(String orderNo){
        BinguoOrder order = binguoOrderRepository.findBy("orderno", orderNo);
        if(order == null){
            return null;
        } else {
            return orderVOTransfer.toOrderVO(order);
        }
    }

    /*public OrderVO findOneByOrderNoWithBalnce(String orderNo,Long balance){
        BinguoOrder order = binguoOrderRepository.findBy("orderno", orderNo);
        if(order == null){
            return null;
        } else {
            return orderVOTransfer.toOrderVOWithBalance(order,balance);
        }
    }*/

    public List<OrderVO> findOrdersBySerialNumber(String serialNumber){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("serialnumber", serialNumber);
        List<BinguoOrder> binguoOrders = binguoOrderRepository.findByCondition(condition);
        if(binguoOrders.isEmpty()){
            return new ArrayList<>();
        }
        return orderVOTransfer.toOrderVOs(binguoOrders);
    }

    public OrderVO findOneByCustomerIdAndOrderNo(Integer customerId, String orderNo){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("orderno", orderNo)
        .andEqualTo("customerid", customerId);
        Optional<BinguoOrder> orderOptional = binguoOrderRepository.findByCondition(condition).stream().findFirst();
        return orderOptional.map(binguoOrder -> orderVOTransfer.toOrderVO(binguoOrder)).orElse(null);
    }



    public List<OrderVOInWX> findWXOrders(Integer customerId, Optional<String> lastOrderNo, Optional<String> searchKey){

                if (lastOrderNo.isPresent()) {
                    if(searchKey.isPresent()) {
                        BinguoOrder binguoOrder = binguoOrderRepository.findBy("orderno", lastOrderNo.get());
                        if (binguoOrder == null) {
                            return new ArrayList<>();
                        }
                        List<BinguoOrder> orders = binguoOrderMapper.findWXByLastOrderNoAndSearchKey(searchKey.get(), customerId, binguoOrder.getId(), 20);
                        return orderVOTransfer.toOrderVOInWX(orders);
                    } else {
                        BinguoOrder binguoOrder = binguoOrderRepository.findBy("orderno", lastOrderNo.get());
                        if (binguoOrder == null) {
                            return new ArrayList<>();
                        }
                        List<BinguoOrder> orders = binguoOrderMapper.findWXByLastOrderNo(customerId, binguoOrder.getId(), 20);
                        return orderVOTransfer.toOrderVOInWX(orders);
                    }


                } else {
                    if(searchKey.isPresent()) {
                        List<BinguoOrder> orders = binguoOrderMapper.findWXBySizeAndSearchKey(searchKey.get(), customerId, 20);
                        if (orders.isEmpty()) {
                            return new ArrayList<>();
                        }
                        return orderVOTransfer.toOrderVOInWX(orders);
                    } else {
                        List<BinguoOrder> orders = binguoOrderMapper.findWXBySize(customerId, 20);
                        if (orders.isEmpty()) {
                            return new ArrayList<>();
                        }
                        return orderVOTransfer.toOrderVOInWX(orders);
                    }
                }



    }


    public List<OrderVOInWX> findShopOrders(Integer shopId,Integer branchId, Optional<String> lastOrderNo, Optional<String> searchKey,Integer isMeal){
        if (lastOrderNo.isPresent()) {
            if(searchKey.isPresent()) {
                //BinguoOrder binguoOrder = binguoOrderRepository.findBy("orderno", lastOrderNo.get());
                BinguoOrder binguoOrder = binguoOrderMapper.findByOrderNo(lastOrderNo.get());
                if (binguoOrder == null) {
                    return new ArrayList<>();
                }
                List<BinguoOrder> orders = binguoOrderMapper.findMealOrder(searchKey.get(), shopId,branchId, binguoOrder.getId(), 20,isMeal);
                return orderVOTransfer.toOrderVOInWX(orders);
            } else {
                /*BinguoOrder binguoOrder = binguoOrderRepository.findBy("orderno", lastOrderNo.get());*/
                BinguoOrder binguoOrder = binguoOrderMapper.findByOrderNo(lastOrderNo.get());
                if (binguoOrder == null) {
                    return new ArrayList<>();
                }
                List<BinguoOrder> orders = binguoOrderMapper.findMealOrder(null,shopId,branchId,binguoOrder.getId(),20,isMeal);
                return orderVOTransfer.toOrderVOInWX(orders);
            }


        } else {
            if(searchKey.isPresent()) {
                List<BinguoOrder> orders = binguoOrderMapper.findMealOrder(searchKey.get(),shopId,branchId,null,20,isMeal);
                if (orders.isEmpty()) {
                    return new ArrayList<>();
                }
                return orderVOTransfer.toOrderVOInWX(orders);
            } else {
                List<BinguoOrder> orders = binguoOrderMapper.findMealOrder(null,shopId,branchId,null,20,isMeal);
                if (orders.isEmpty()) {
                    return new ArrayList<>();
                }
                return orderVOTransfer.toOrderVOInWX(orders);
            }
        }



    }

    public List<OrderVO> findPayCardOrder(Integer cardId){

        List<BinguoOrder> orders = binguoOrderMapper.findPayCardOrder(cardId);
        if(orders.isEmpty()) {
            return null;
        }
        return orderVOTransfer.toOrderVOs(orders);


    }

    public Optional<BinguoOrder> findLastOrder(Integer shopId, Integer cashierDeskId) {
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("shopid", shopId)
                .andEqualTo("cashierdeskid", cashierDeskId)
                .andNotEqualTo("paystatus", 0);
        condition.orderBy("created").desc();
       return binguoOrderRepository.findByCondition(condition).stream().findFirst();

    }

    public List<SMStatisticsOrderVO> getSMOrderByDeskId(Integer cashierDeskId){
        String startTime;
        String endTime;
        Integer count = 0;
        Long sum = 0L;
        List<SMStatisticsOrderVO> smStatisticsOrderVOS = new ArrayList<>();

        startTime = dateTimeFormat.format(DateHelper.getBeginDayOfLastMonth());
        endTime = dateTimeFormat.format(DateHelper.getEndDayOfLastMonth());
        SMStatisticsOrderVO smStatisticsOrderVO = new SMStatisticsOrderVO();
        List<SMStatisticsOrderVO> smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){
            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(5);
        //smStatisticsOrderVO.setMonth(String.valueOf(DateHelper.getLastMonth()));
        smStatisticsOrderVOS.add(smStatisticsOrderVO);

        //上上月
        startTime = dateTimeFormat.format(DateHelper.getBeginDayOfLastMonthLastMonth());
        endTime = dateTimeFormat.format(DateHelper.getEndDayOfLastMonthLastMonth());
        smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){
            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO = new SMStatisticsOrderVO();
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(6);
        //smStatisticsOrderVO.setMonth(String.valueOf(DateHelper.getLastLastMonth()));
        smStatisticsOrderVOS.add(smStatisticsOrderVO);
        //本月
        startTime = dateTimeFormat.format(DateHelper.getBeginDayOfMonth());
        endTime = dateTimeFormat.format(DateHelper.getEndDayOfMonth());
        Map<String,Long> SMSalesByDay = new HashMap<>();
        Map<String,Integer> SMSalesCountByDay = new HashMap<>();
        smStatisticsOrderVO = new SMStatisticsOrderVO();
        smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){
            SMSalesByDay.put(smStatisticsOrderDayVO.getPayTime(),smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee());
            SMSalesCountByDay.put(smStatisticsOrderDayVO.getPayTime(),smStatisticsOrderDayVO.getCount());
            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(4);
        smStatisticsOrderVOS.add(smStatisticsOrderVO);
        count = 0;
        sum = 0L;
        //今日
        smStatisticsOrderVO = new SMStatisticsOrderVO();
        startTime = dateTimeFormat.format(DateHelper.getDayBegin());
        endTime = dateTimeFormat.format(DateHelper.getDayEndTime(DateHelper.getDayBegin()));
        smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){
            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(1);
        smStatisticsOrderVOS.add(smStatisticsOrderVO);
        count = 0;
        sum = 0L;
        //昨日
        smStatisticsOrderVO = new SMStatisticsOrderVO();
        startTime = dateTimeFormat.format(DateHelper.getBeginDayOfYesterday());
        endTime = dateTimeFormat.format(DateHelper.getDayEndTime(DateHelper.getBeginDayOfYesterday()));
        smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){

            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(2);
        smStatisticsOrderVOS.add(smStatisticsOrderVO);
        count = 0;
        sum = 0L;
        //本周
        smStatisticsOrderVO = new SMStatisticsOrderVO();
        startTime = dateTimeFormat.format(DateHelper.getBeginDayOfWeek());
        endTime = dateTimeFormat.format(DateHelper.getEndDayOfWeek());
        smStatisticsOrderVOList = binguoOrderMapper.getSMStatistics(cashierDeskId,startTime,endTime);
        for (SMStatisticsOrderVO smStatisticsOrderDayVO : smStatisticsOrderVOList){
            sum += smStatisticsOrderDayVO.getRealFee() - smStatisticsOrderDayVO.getRefundFee();
            count += smStatisticsOrderDayVO.getCount();
        }
        smStatisticsOrderVO.setCount(count);
        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
        smStatisticsOrderVO.setType(3);
        smStatisticsOrderVOS.add(smStatisticsOrderVO);
//        if (SMSalesByDay.get(todayDate) == null) {
//            smStatisticsOrderVO.setMoneyStr("0.00");
//        }else {
//            smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(SMSalesByDay.get(todayDate)));
//
//        }
//        if (SMSalesCountByDay.get(todayDate) == null) {
//            smStatisticsOrderVO.setCount(0);
//        }else {
//            smStatisticsOrderVO.setCount(SMSalesCountByDay.get(todayDate));
//        }
//        smStatisticsOrderVOS.add(smStatisticsOrderVO);
//
//        //昨日
//        String yestodayDate = dateFormat.format(DateHelper.getBeginDayOfYesterday());
//        smStatisticsOrderVO = new SMStatisticsOrderVO();
//        smStatisticsOrderVO.setType(2);
//        if (SMSalesByDay.get(yestodayDate) == null) {
//            smStatisticsOrderVO.setMoneyStr("0.00");
//        }else {
//            smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(SMSalesByDay.get(yestodayDate)));
//
//        }
//        if (SMSalesCountByDay.get(yestodayDate) == null) {
//            smStatisticsOrderVO.setCount(0);
//        }else {
//            smStatisticsOrderVO.setCount(SMSalesCountByDay.get(yestodayDate));
//        }
//        smStatisticsOrderVOS.add(smStatisticsOrderVO);
//
//        //本周
//        smStatisticsOrderVO = new SMStatisticsOrderVO();
//        Date weekStartTime = DateHelper.getBeginDayOfWeek();
//        Calendar calendar = Calendar.getInstance();
//        sum = 0L;
//        count = 0;
//        for (int i = 0 ;i < 7; i++){
//            String weekDate = dateFormat.format(weekStartTime);
//            if (SMSalesByDay.get(weekDate) != null) {
//                sum += SMSalesByDay.get(weekDate);
//            }
//            if (SMSalesCountByDay.get(weekDate) != null) {
//                count += SMSalesCountByDay.get(weekDate);
//            }
//            calendar.setTime(weekStartTime);
//            calendar.add(Calendar.DATE,1);
//            weekStartTime = calendar.getTime();
//        }
//        smStatisticsOrderVO.setCount(count);
//        smStatisticsOrderVO.setMoneyStr(PriceUtil.changeF2Y(sum));
//        smStatisticsOrderVO.setType(3);
//        smStatisticsOrderVOS.add(smStatisticsOrderVO);

        return smStatisticsOrderVOS;
    }


    public List<OrderVO> findOrders(Integer shopId, Integer cashierDeskId, Optional<Integer> orderStatus, Optional<String> lastOrderNo){

        if(lastOrderNo.isPresent()){
            BinguoOrder binguoOrder =  binguoOrderRepository.findBy("orderno", lastOrderNo.get());
            if (binguoOrder == null) {
                return null;
            }

            if(orderStatus.isPresent()){
                if(orderStatus.get().equals(OrderStatus.PAY_SUCCEES.getCode())){
                    List<BinguoOrder> orders = binguoOrderMapper.findPaySuccessByLastOrderNo(shopId, cashierDeskId, binguoOrder.getId(), 20);
                    return orderVOTransfer.toOrderVOs(orders);
                }
                if(orderStatus.get().equals(OrderStatus.REFUND_SUCCEES.getCode())){
                    List<BinguoOrder> orders = binguoOrderMapper.findRefundSuccessByLastOrderNo(shopId, cashierDeskId, binguoOrder.getId(), 20);
                    return orderVOTransfer.toOrderVOs(orders);
                }
            }

            List<BinguoOrder> orders = binguoOrderMapper.findByLastOrderNo(shopId, cashierDeskId, binguoOrder.getId(), 20);
            return orderVOTransfer.toOrderVOs(orders);

        } else {
            if(orderStatus.isPresent()) {
                if(orderStatus.get().equals(OrderStatus.PAY_SUCCEES.getCode())){
                    List<BinguoOrder> orders = binguoOrderMapper.findPaySuccessBySize(shopId, cashierDeskId, 20);
                    return orderVOTransfer.toOrderVOs(orders);
                }
                if(orderStatus.get().equals(OrderStatus.REFUND_SUCCEES.getCode())){
                    List<BinguoOrder> orders = binguoOrderMapper.findRefundSuccessBySize(shopId, cashierDeskId, 20);
                    return orderVOTransfer.toOrderVOs(orders);
                }
            }

            List<BinguoOrder> orders = binguoOrderMapper.findBySize(shopId, cashierDeskId, 20);
            return orderVOTransfer.toOrderVOs(orders);

        }

    }

    public void updateOrder(OrderDTO orderDTO){
        BinguoOrder order = binguoOrderRepository.findBy("orderno", orderDTO.getOrderNo());
        order.setEmployeeid(employeeLoginHistoryMapper
                .getEmployeeId(orderDTO.getCashierDeskId()));
        binguoOrderRepository.update(order);
        if (!orderDTO.getRealFee().equals(orderDTO.getTotalFee())){
            DiscountOrder discountOrder = new DiscountOrder();
            discountOrder.setCreated(new Date());
            discountOrder.setCustomerid(order.getCustomerid());
            discountOrder.setShopid(order.getShopid());
            discountOrder.setOrderid(order.getId());
            discountOrderRepository.save(discountOrder);
        }
        Shop shop = shopService.findShopById(orderDTO.getShopId());
        if (shop.getPayType().equals(9) && order.getOrdertype().equals(5)){
            PayCard payCard = customerService.getCustomerPayCard(order.getCustomerid(),order.getShopid());
            if (payCard == null){
                payCard = customerService.createPayCard(order.getCustomerid(),order.getShopid());
            }

            Condition condition = new Condition(ShiminkaRechargeDiscount.class);
            condition.or().andEqualTo("shopid",shop.getId())
                    .andEqualTo("status",1);
            List<ShiminkaRechargeDiscount> shiminkaRechargeDiscountList = shiminkaRechargeDiscountRepository.findByCondition(condition);
            for (ShiminkaRechargeDiscount shiminkaRechargeDiscount : shiminkaRechargeDiscountList){
                if (order.getPaytime().after(shiminkaRechargeDiscount.getStarttime()) && order.getPaytime().before(shiminkaRechargeDiscount.getEndtime())){
                    Condition disCountCondition = new Condition(ShiminkaRecharge.class);
                    disCountCondition.or().andEqualTo("customerid",order.getCustomerid())
                            .andEqualTo("shopid",order.getShopid())
                            .andEqualTo("rechargediscountid",shiminkaRechargeDiscount.getId());
                    List<ShiminkaRecharge> rechargeList = shiminkaRechargeRepository.findByCondition(disCountCondition);
                    if (null == rechargeList || rechargeList.size() == 0){
                        ShiminkaRecharge shiminkaRecharge = new ShiminkaRecharge();
                        shiminkaRecharge.setCustomerid(order.getCustomerid());
                        shiminkaRecharge.setShopid(order.getShopid());
                        shiminkaRecharge.setRechargediscountid(shiminkaRechargeDiscount.getId());
                        Long rechargeMoney = shiminkaRechargeDiscount.getRechargemoney();
                        shiminkaRecharge.setOrdermoney(order.getRealfee()%rechargeMoney);
                        shiminkaRechargeRepository.save(shiminkaRecharge);
                        Long discountNum = order.getRealfee() / rechargeMoney;
                        Long discountMoney = shiminkaRechargeDiscount.getDiscountmoney();
                        if (discountNum>0){
                            //SMS sms = JavaSmsApi.sendRechargeVerify(order.getCustomerphone(),PriceUtil.changeF2Y(discountNum * discountMoney),shop.getName());
                            SMS sms = JavaSmsApi.sendRechargeVerify(order.getCustomerphone(),PriceUtil.changeF2Y(discountNum * discountMoney),"老年食堂");
                            logger.info(sms.getMsg());
                        }
                        payCard.setAccountbalance(payCard.getAccountbalance() + discountNum * discountMoney);
                        payCardRepository.update(payCard);
                    }else {
                        ShiminkaRecharge shiminkaRecharge = rechargeList.get(0);
                        Long orderMoney = shiminkaRecharge.getOrdermoney()+order.getRealfee();
                        Long rechargeMoney = shiminkaRechargeDiscount.getRechargemoney();
                        shiminkaRecharge.setOrdermoney(orderMoney%rechargeMoney);
                        shiminkaRechargeRepository.update(shiminkaRecharge);
                        Long discountNum = orderMoney / rechargeMoney;
                        Long discountMoney = shiminkaRechargeDiscount.getDiscountmoney();
                        if (discountNum>0){
                            //SMS sms = JavaSmsApi.sendRechargeVerify(order.getCustomerphone(),PriceUtil.changeF2Y(discountNum * discountMoney),shop.getName());
                            SMS sms = JavaSmsApi.sendRechargeVerify(order.getCustomerphone(),PriceUtil.changeF2Y(discountNum * discountMoney),"老年食堂");
                            logger.info(sms.getMsg());
                        }
                        payCard.setAccountbalance(payCard.getAccountbalance() + discountNum * discountMoney);
                        payCardRepository.update(payCard);
                    }
                    break;
                }
            }
        }
    }

    public void saveOrderUrl(String serialNumber,Integer shopID, String filename){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("serialnumber",serialNumber)
                .andEqualTo("shopid",shopID);
        List<BinguoOrder> binguoOrderList = binguoOrderRepository.findByCondition(condition);
        if (null == binguoOrderList || binguoOrderList.size() == 0){
            throw new ServiceException("不存在该订单");
        }
        BinguoOrder binguoOrder = binguoOrderList.get(0);
        binguoOrder.setProductOrderUrl(filename);
        binguoOrderRepository.update(binguoOrder);
    }

    public List<OrderVOInWX> getTodayOrderByCustomerId(Integer customerId,
                                          Integer shopId){

        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("shopid",shopId)
                .andEqualTo("customerid",customerId)
                .andEqualTo("ordertype",4)
                .andBetween("created",dateTimeFormat.format(DateHelper.getDayBegin()),dateTimeFormat.format(DateHelper.getDayEnd()));
        List<BinguoOrder> orderList = binguoOrderRepository.findByCondition(condition);

        return orderVOTransfer.toOrderVOInWX(orderList);
    }

    public JSONObject getTodayReserveOrder(Integer branchId){

        List<String> dayStrList = new ArrayList<>();

        JSONObject result = new JSONObject();

        String todayStr = dateFormat.format(DateHelper.getDayEnd());
        dayStrList.add(todayStr);

        String yesterDayStr = dateFormat.format(DateHelper.getBeginDayOfYesterday());
        dayStrList.add(yesterDayStr);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateHelper.getDayBegin());
        calendar.add(Calendar.DATE, -2);

        String dayBeforeYesterDayStr = dateFormat.format(calendar.getTime());
        dayStrList.add(dayBeforeYesterDayStr);

        List<ReserveOrderVO> orderList = binguoOrderMapper.sumReserveOrder(dateTimeFormat.format(calendar.getTime()),dateTimeFormat.format(DateHelper.getDayEnd()),branchId);

        if (null != orderList && orderList.size() > 0){
            JSONArray dayList = new JSONArray();
            String dateStr = orderList.get(0).getDate();
            for (ReserveOrderVO orderVO:orderList){
                if (!dateStr.equals(orderVO.getDate())) {
                    for (int i = 0;i<dayStrList.size();i++){
                        if (dateStr.equals(dayStrList.get(i))){
                            result.put(i+"",dayList);
                            break;
                        }
                    }
                    dayList = new JSONArray();
                    dateStr = orderVO.getDate();
                }
                JSONObject product = (JSONObject) JSONObject.toJSON(orderVO);
                dayList.add(product);
            }
            for (int i = 0;i<dayStrList.size();i++){
                if (dateStr.equals(dayStrList.get(i))){
                    result.put(i+"",dayList);
                    break;
                }
            }
        }


        return result;
    }

    public void reserveOrderPay(String orderNo){
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andEqualTo("orderno",orderNo);
        List<BinguoOrder> orderList = binguoOrderRepository.findByCondition(condition);
        if (null == orderList || orderList.size() == 0){
            throw new ServiceException("订单不存在");
        }
        BinguoOrder order = orderList.get(0);

        if (order.getPaystatus().equals(0)){
            PayCard payCard = payCardRepository.findById(order.getCardid());
            Long realFee = order.getRealfee();

            Long balance = payCard.getAccountbalance();
            Long wxBalance = payCard.getWxAccountbalance();
            Long yktBalance = payCard.getYktAccountbalance();
            Long bzBalance = payCard.getBzAccountbalance();

            Long bzNewBalance = bzBalance - realFee;
            Long yktNewBalance = yktBalance - realFee+ bzBalance;
            Long wxNewBalance = wxBalance - realFee + yktBalance + bzBalance;
            Long newBalance = balance - realFee + yktBalance + bzBalance + wxBalance;

            if (bzNewBalance >= 0){
                payCard.setBzAccountbalance(bzNewBalance);
            }else if (yktNewBalance >= 0) {
                payCard.setBzAccountbalance(0L);
                payCard.setYktAccountbalance(yktNewBalance);
            }else if (wxNewBalance >= 0) {
                payCard.setBzAccountbalance(0L);
                payCard.setYktAccountbalance(0L);
                payCard.setWxAccountbalance(wxNewBalance);
            } else if (newBalance >= 0){
                payCard.setYktAccountbalance(0L);
                payCard.setBzAccountbalance(0L);
                payCard.setWxAccountbalance(0L);
                payCard.setAccountbalance(newBalance);
            }else {
                throw new ServiceException(PAYCARD_NOT_SUFFICIENT_FUNDS);
            }
        }
    }

    public BinguoOrderVO getSurcharge(String orderId){
       return binguoOrderMapper.findIsMealByOrderNo(orderId);
    }

    /*public List<BinguoOrder> getOrderCount(){
        Date today = new Date();
        JSONObject result = new JSONObject();
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(1);
        orderTypeList.add(4);
        orderTypeList.add(5);
        orderTypeList.add(6);
        Condition condition = new Condition(BinguoOrder.class);
        condition.or().andIn("ordertype",orderTypeList)
                .andEqualTo("paystatus",1)
                .andBetween("paytime",dateFormat.format(today)+" 00:00:00",dateFormat.format(today)+" 23:59:59");

        List<BinguoOrder> binguoOrderList = binguoOrderRepository.findByCondition(condition);

        return binguoOrderList;
    }*/

}
